<?php

/*
 * 商品类
 *
 */

namespace Home\Logic;

class ShopitemLogic {

    const PUT_AWAY = 1;
    const SOLD_OUT = 2;
    const DELETE_OUT = 0;

    public function __construct() {
        $this->st = D('Shop_item');
        $this->si = new \Home\Logic\ShopitemimageLogic();
        $this->sms = new \Home\Logic\ShopmealsetLogic();
        import('Memcachectr');
        $this->m = \Think\Memcachectr::create();
    }
    
    public function setStoreId($store_id){
        $this->st->setTableNamePre($store_id);
    }

    public function getItemsByStoreIds($store_id, $status = false) {
        if (is_array($store_id)) {
            $item = array();
            foreach ($store_id as $v) {
                $arr = $this->getItemsByStoreId($v, $status);
                foreach($arr as $v){
                    $item[] = $v;
                }
            }
            return $item;
        } else {
            return $this->getItemsByStoreId($store_id,$status);
        }
    }

    public function getItemsByIds($ids,$store_id,$bool=false) {
        $item = array();
        foreach ((array)$ids as $v) {
            $item[] = $this->getItemById($v,$store_id,$bool);
        }
        return $item;
    }

    public function getItemsByStoreId($store_id, $status=false) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $key = $status === false ? 'store_items_' . $store_id : 'store_items_' . $store_id . "_" . $status;
        $this->m->delete($key);
        $items = $this->m->get($key);
        if (!$items) {
            $where = 'store_id=' . $store_id;
            if ($status == false) {
                $where .= ' and status != 0';
            }else{
                $where .= ' and status = '.$status;
            }
            $sql = "select * from ( select * from shop_item_".substr($store_id,-1)." where " . $where . "  order by id desc ) as a group by a.item_number order by id desc";
            $items = $this->st->_read_data($this->st->query($sql));
            foreach ($items as $k => $v) {
                $items[$k]['images'] = $this->si->getImageByItemId($v['id'],$store_id);
                $type = $v['type'];
                if ($type == 0) {
                    $items[$k]['img'] = 'lf.png';
                } elseif ($type == 1) {
                    $items[$k]['img'] = 'tr.png';
                } elseif ($type == 2) {
                    $items[$k]['img'] = 'hl.png';
                } elseif ($type == 3) {
                    $items[$k]['img'] = 'yq.png';
                } elseif ($type == 4) {
                    $items[$k]['img'] = 'rg.png';
                }
            }
            $this->m->set($key, $items, true);
        }
        return $items;
    }


    //获得单品
    public function getItem($store_id){
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $where = 'store_id='.$store_id.' and status = 1 and is_meal_set = 0 ';
        $sql = "select * from ( select * from shop_item_".substr($store_id,-1)."  where ".$where."  order by id desc ) as a group by a.item_number order by id desc";
        $items = $this->st->_read_data($this->st->query($sql));
        return $items;
    }

    public function getItemById($id,$store_id,$bool=false) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $this->m->delete('item_' .$store_id.'_'. $id);
        $item = $this->m->get('item_' .$store_id.'_'. $id);
        if (!$item) {
            if($bool){
                $where = 'id=' . $id;
            }else{
                $where = 'id=' . $id.' and status!=0';
            }
            $item = $this->st->where($where)->order('id desc')->limit(1)->find();
            if($item){
                $type = $item['type'];
                if ($type == 0) {
                    $item['img'] = 'lf.png';
                } elseif ($type == 1) {
                    $item['img'] = 'tr.png';
                } elseif ($type == 2) {
                    $item['img'] = 'hl.png';
                } elseif ($type == 3) {
                    $item['img'] = 'yq.png';
                } elseif ($type == 4) {
                    $item['img'] = 'rg.png';
                }
                $item['images'] = $this->si->getImageByItemId($id,$store_id);
                if($item['is_meal_set']==1){
                    $meal = new \Home\Logic\ShopmealsetLogic();
                    $items = $meal->getItemByMealSetId($id,$store_id,$bool);
                    foreach($items as $k=>$v){
                        $name = $this->getItemById($v['item_id'],$store_id,$bool);
                        $arr=array('name'=>$name['name'],'number'=>$v['number'],'item_id'=>$name['id'],'item_number'=>$name['item_number']);
                        $item['items'][$k]= $arr;
                    } 
                }
            }
            $this->m->set('item_' .$store_id.'_'. $id, $item, true);
        }
        return $item;
    }

    public function getItemByIds($ids,$store_id) {
        $ids = explode(',', $ids);
        foreach ((array) $ids as $v) {
            $arr[] = $this->getItemById($v,$store_id);
        }
        return $arr;
    }

    public function getItemByNumber($number,$store_id) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $item = $this->m->get('item_number_' . $number);
        if (!$item) {
            $item = $this->st->where("item_number='$number' and status!=0")->order('id desc')->limit(1)->find();
            $item['images'] = $this->si->getImageByItemId($item['id'],$store_id);
            $this->m->set('item_number_' . $number, $item, true);
        }
        return $item;
    }
    
    //按item_id获取套餐中的单品
    public function getItemByMealSetId($meal_set_id,$store_id,$bool = false){
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $sms = new \Home\Logic\ShopmealsetLogic();
        $items_set = $sms->getItemByMealSetId($meal_set_id,$store_id);
        $items = array();
        foreach((array)$items_set as $k=>$v){
            $items[$k] = $this->getItemById($v['item_id'],$store_id,$bool);
            $items[$k]['number'] = $v['number'];

        }
        return $items;
    }

    public function getItemByMealSetNumber($meal_set_number,$store_id) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $sms = D('Shopmealset', 'Logic');
        $items_set = $this->sms->getItemByMealSetId($meal_set_number,$store_id);
        $items = array();
        foreach ((array) $items_set as $v) {
            $items[] = $this->getItemById($v['item_id'],$store_id);
        }
        return $items;
    }

    public function insertItem($data) {
        if($data['store_id']<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($data['store_id']);
        $this->m->delete('store_items_' . $data['store_id']);
        $this->m->delete('store_items_'.$data['store_id']."_2");
        if($data['item_number']){
            $this->m->delete('item_number_' . $data['item_number']);
        }
        return $this->st->add($data);
    }

    /* 商品下架 */

    public function soldOut($id,$store_id) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $re = $this->st->where('id=' . $id)->save(array('status' => self::SOLD_OUT));
        $item = $this->getItem($id);
        $this->m->get('item_number_' . $item['item_number']);
        $this->m->delete('item_' . $id);
        $this->m->delete('store_items_' . $store_id);
        $this->m->delete('item_' .$store_id.'_'. $item['id']);
        $this->m->delete('store_items_'.$data['store_id']."_".$item['item_number']);
        $this->m->delete('store_items_'.$data['store_id']."_1");
        $this->m->delete('store_items_'.$data['store_id']."_2");
        return $re;
    }

    /* 商品上架 */

    public function putAway($id, $store_id) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $re = $this->st->where('id=' . $id)->save(array('status' => self::PUT_AWAY));
        $item = $this->getItem($id);
        $this->m->get('item_number_' . $item['item_number']);
        $this->m->delete('item_' .$store_id.'_'. $id);
        $this->m->delete('store_items_' . $store_id);
        $this->m->delete('item_' .$store_id.'_'. $item['id']);
        $this->m->delete('store_items_'.$data['store_id']."_".$item['item_number']);
        $this->m->delete('store_items_'.$data['store_id']."_1");
        $this->m->delete('store_items_'.$data['store_id']."_2");
        return $re;
    }

    /* 商品删除 */

    public function deleteItem($id, $store_id) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $re = $this->st->where('id=' . $id)->save(array('status' => self::DELETE_OUT));
        $item = $this->getItem($id);
        $this->m->get('item_number_' . $item['item_number']);
        $this->m->delete('item_' .$store_id.'_'. $id);
        $this->m->delete('store_items_' . $store_id);
        $this->m->delete('item_' .$store_id.'_'. $item['id']);
        $this->m->delete('store_items_'.$data['store_id']."_".$item['item_number']);
        $this->m->delete('store_items_'.$data['store_id']."_0");
        $this->m->delete('store_items_'.$data['store_id']."_2");
        return $re;
    }

    
    /*更新商品*/
    public function updateItem($item_number,$store_id){
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        //更新完后注意清除item 缓存，store_item 缓存，图片缓存
        $status =array('status'=>0);
        $where = " item_number='$item_number'";
        $re = $this->st->where($where)->save($status);
        $this->m->get('item_number_' . $item_number);
        $this->m->delete('item_' .$store_id.'_'. $re['id']);
        $this->m->delete('store_items_'.$data['store_id']);
        $this->m->delete('store_items_'.$data['store_id']."_".$item_number);
        $this->m->delete('store_items_'.$data['store_id']."_0");
        $this->m->delete('store_items_'.$data['store_id']."_1");
        $this->m->delete('store_items_'.$data['store_id']."_2");
        return $re;
    }

    public function search($store_id, $start = 0, $status = 1, $type) {
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        if ($store_id > 0) {
            $where .= 'store_id = ' . $store_id;
        }
        if ($type != 0) {
            if ($type == 2) {
                $type = 0;
            }
            $where .=' and is_meal_set = ' . $type;
        }
        if ($status) {
            $wh = ' where status = ' . $status;
        }else{
            $wh = ' where status != 0'; 
        }
        $sql = "select * from (select * from ( select * from shop_item_".substr($store_id,-1)."   where " . $where . "  order by id desc ) as a group by a.item_number order by id desc) as b " . $wh . " order by id desc limit " . $start . ",12";
        $items = $this->st->_read_data($this->st->query($sql));
        foreach ($items as $k => $v) {
            $items[$k]['images'] = $this->si->getImageByItemId($v['id'],$store_id);
            $type = $v['type'];
            if ($type == 0) {
                $items[$k]['img'] = 'lf.png';
            } elseif ($type == 1) {
                $items[$k]['img'] = 'tr.png';
            } elseif ($type == 2) {
                $items[$k]['img'] = 'hl.png';
            } elseif ($type == 3) {
                $items[$k]['img'] = 'yq.png';
            } elseif ($type == 4) {
                $items[$k]['img'] = 'rg.png';
            }
        }
        return $items;
    }


    public function thingInsertItem($data,$arr){
        $this->st->startTrans();
        $id = $this->insertItem($data);
        $data['item_id'] = $id;
        $data['status'] = 1;
        $image = $this->si->thingInsertImage($data,$type=1);
        if($image===false){
                $this->st->rollback();
                return false;
        }
        if($data['is_meal_set']==1){
            $arr['meal_set_number'] = $data['item_number'];
            $arr['meal_set_id'] = $id;
            $insertMeal = $this->sms->thingInsertMealset($arr,$arr['meal_set_id'],$arr['meal_set_number'],$arr['store_id'],$type=1);
            if($insertMeal===false){
                $this->st->rollback();
                return false;
            }   
        }
        if($id<1){
            $this->st->rollback();
            return false;
        }
        $this->st->commit();
        return $id;

    }



    public function thingUpdateItem($data,$getItem,$meal,$_item){
        $this->st->startTrans();
        $re = $this->updateItem($data['item_number'],$data['store_id']);
        $id = $this->insertItem($data);
        //$image = $this->si->thingUpdateImage($data,$getItem,$data['store_id']);  
        
            $data['item_id'] = $id;
            $data['status'] = 1;
            $insertImage = $this->si->thingInsertImage($data,$type=0);
            if($insertImage===false ){
                $this->st->rollback();
                return false;
            }
        
        if($data['is_meal_set']==1){
            //$update = $this->sms->thingUpdateMealset($meal,$data['store_id']);
            $insert = $this->sms->thingInsertMealset($_item,$id,$data['item_number'],$data['store_id'],$type=0);
            if($insert===false){
                $this->st->rollback();
                return false;  
            }
        }
        if($re<1 || $id<1  ){
            $this->st->rollback();
            return false;
        }
        $this->st->commit();
        return $id;

    }


    public function cartAddin($session_id,$item_id,$store_id){
        $item = $this->getItemById($item_id,$store_id,true);
        $_SESSION['carts'][$store_id.'C'.$item_id] =$item['item_number'];
        if($this->m->get($session_id)){
            $cart = $this->m->get($session_id);
            $cart['carts'][$store_id.'C'.$item_id] =$item['item_number'];
            $re =$this->m->set($session_id,$cart,false,0);
        }else{
            $cart['carts'][$store_id.'C'.$item_id] =$item['item_number'];
            $re = $this->m->set($session_id,$cart,false,0);
        }
        return $re;
    }

    public function cartDelfrom($session_id,$item_number,$store_id){
        $cart = $this->m->get($session_id);
        foreach($cart['carts'] as $k=>$v){
            if($v==$item_number){
                $cart['carts'][$k]='';
                $_SESSION['carts'][$k]='';
            }
        }
        $re = $this->m->set($session_id,$cart,false,0); 
        return $re;
    }

    //user 用
    public function userGetItem($id,$store_id){
        if($store_id<1){
            throw new \Exception('shop_id is null');
        }
        $this->setStoreId($store_id);
        $where = 'store_id='.$store_id.' and status = 1 and id='.$id;
        $item= $this->st->where($where)->find();
        return $item;
    }


}

